package com.nova.edc.service.system.impl;

import java.util.ArrayList;
import java.util.List;

import com.nova.edc.service.system.RoleService;
import org.springframework.beans.factory.annotation.Autowired;

import com.nova.edc.dao.system.RoleMenuDao;
import com.nova.edc.model.system.ModelConstant;
import com.nova.edc.model.system.RoleMenu;
import com.nova.edc.service.system.RoleMenuService;
import com.nova.frame.dao.buzz.query.Order;
import com.nova.frame.dao.buzz.query.Query;
import com.nova.frame.dao.criterion.Restrictions;

public class RoleMenuServiceImpl implements RoleMenuService {

    @Autowired
    private RoleMenuDao novaRoleMenuDao;

    @Autowired
    private RoleService novaroleService;
    @Override
    public List<RoleMenu> findAll() {
        return novaRoleMenuDao.findAll();
    }

    @Override
    public List<RoleMenu> findMenuByRole(Integer roleid, Integer customerinfotype, Integer architecturetype) {
        Query<RoleMenu> query = novaRoleMenuDao.query()
                .add(Restrictions.eq("Roleid", roleid))
                .addOrder(Order.custom("asc", "Ord"));
        if (novaroleService.getById(roleid).getRoletype()!= ModelConstant.ROLE_SYSTEM) {

            if (customerinfotype != null && customerinfotype != 0) {
                query.add(Restrictions.eq("Customerinfotype", customerinfotype));
            }
        }
        List<RoleMenu> menus = query.list();
        List<RoleMenu> leftMenus = new ArrayList<RoleMenu>();
        for (int i = 0; i < menus.size(); i++) {
            if (menus.get(i).getLevel() != null && menus.get(i).getLevel() == ModelConstant.MENU_FIRST) {
                leftMenus.add(menus.get(i));
            }
        }
        for (int i = 0; i < leftMenus.size(); i++) {
            List<RoleMenu> childMenus = new ArrayList<RoleMenu>();
            for (int j = 0; j < menus.size(); j++) {
                if (menus.get(j).getLevel() != null && menus.get(j).getLevel() == ModelConstant.MENU_SECOND
                        && menus.get(j).getParentid() == leftMenus.get(i)
                        .getMenuid()) {
                    childMenus.add(menus.get(j));
                }
            }
            if (childMenus.size() != 0) {
                leftMenus.get(i).setChildMenus(childMenus);
            }
        }
        return leftMenus;
    }
}
